/**
 * Created by xxx on 2017/7/14.
 * 通讯录
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link
} from 'react-router'

import {
    HttpService,
    Tips,
    browser,
    getDefaultImg
} from '../Tools'

import Header from './Common/Header'
import ConfirmBox from './Common/ConfirmBox'

/*
 *通讯录-教师、家长
 */
export default class PhoneDirectories extends Component {
    constructor(props) {
        super(props);
        this.area = new LArea();
        this.state = {
            type: true, //true教师，false 家长
            footerList: false,
            footerDepartment: [],
            footerGrade: [],
            footerClass: [],
            listData: [], //电话列表数据
            queryListData: [], //查询-电话列表数据
            queryData: [], //查询出来的数据
            search: false, //输入框是否有值
            footerMenu: 1, //1管理员 2 年级 3 班级
            showModule: false, //防止多次点击被app捕获调用打电话
        }
    }

    componentWillMount() {

        //查询部门
        HttpService.query({
            url: '/jxt-api/rest/oauth',
            data: {
                method: 'org.list',
                req: '{"entry": "user","userid":"' + sessionStorage.userid + '","isdept": "null"}',
                appkey: 'oauthsp',
                sign: '4a553e943f3e4d990f4f822826099c1c',
                v: '1.0'
            },
            success: (res => {
                if (res.msgcode == '0000') {
                    let data = res.body[0];
                    if (data != null && data.length > 0) {
                        this.setData(data[0], true, 0, data.length);
                        for (let i = 1; i < data.length; i++) {
                            this.setData(data[i], false, i, data.length);
                        }
                        this.setState({
                            footerClass: this.state.footerClass,
                            footerGrade: this.state.footerGrade,
                            footerDepartment: this.state.footerDepartment
                        });
                    } else {
                        Tips('没有查找到部门相关数据！');
                    }
                } else {
                    Tips(res.msg);
                }
            })
        })
    }
    componentDidUpdate() {
        if (sessionStorage.userrole == '家长') {
            return;
        }
        const {
            footerClass,
            footerGrade,
            footerDepartment,
            type
        } = this.state;
        let leftData = [],
            rightData = {};
        if (footerDepartment.length > 0 && type) {
            leftData.push({
                "name": "部门",
                "value": "110000",
                "id": "bumen"
            });
            rightData['110000'] = footerDepartment;
        }
        if (footerGrade.length > 0) {
            leftData.push({
                "name": "年级",
                "value": "120000",
                "id": "lianji"
            });
            rightData['120000'] = footerGrade;
        }
        if (footerClass.length > 0) {
            leftData.push({
                "name": "班级",
                "value": "130000",
                "id": "banji"
            });
            rightData['130000'] = footerClass;
        }
        if (leftData.length > 0) {
            this.area.init({
                'trigger': '.color_blue',
                'valueTo': '#footer_select',
                'keys': {
                    id: 'value',
                    name: 'name',
                    ids: 'id',
                    type: 'type',
                    selected: 'selected',
                },
                'type': 2,
                'data': [leftData, rightData]
            });
        }
    }
    /**
     * 设置值
     */
    setData(dataInfo, selectedType, leng, dataLeng) {
        const {
            footerClass,
            footerGrade,
            footerDepartment
        } = this.state;
        if (dataInfo[4] == 0) { //班级
            footerClass.push({
                name: dataInfo[1],
                id: dataInfo[0],
                type: false,
                selected: selectedType,
                value: (footerClass.length + 1) * 100 + 130000
            });
        } else if (dataInfo[4] == 1) { //年级
            if (dataInfo[3] == '校管理员') {
                this.getGrade(selectedType); //调用API-5接口
                // footerGrade.push({name:dataInfo[3],id:dataInfo[0],type:true,selected:selectedType});
            } else {
                // footerGrade.push({
                //     name: dataInfo[1],
                //     id: dataInfo[0],
                //     type: false,
                //     selected: selectedType,
                //     value: (footerGrade.length + 1) * 100 + 120000
                // });
            }
        } else if (dataInfo[4] == 2) { //部门
            if (dataInfo[3] == '校管理员') {
                footerDepartment.push({
                    deptname: dataInfo[3],
                    name: dataInfo[1],
                    id: dataInfo[0],
                    type: true,
                    selected: selectedType,
                    value: (footerDepartment.length + 1) * 100 + 110000
                });
            } else {
                footerDepartment.push({
                    deptname: dataInfo[3],
                    name: dataInfo[1],
                    id: dataInfo[0],
                    type: false,
                    selected: selectedType,
                    value: (footerDepartment.length + 1) * 100 + 110000
                });
            }
        }
        if (leng == dataLeng - 1) {
            this.setType(true);
        }
    }

    /*
    APP 即时聊天
     */
    pushToChatRoom(str, e) {
        console.log(str);
        e.preventDefault();
        if (sessionStorage.wherefrom == 'ios') {
            window.webkit.messageHandlers.pushToChatRoom.postMessage(str);
        } else {
            appweb.pushToChatRoom(str)
        }
    }

    /**
     * 获取年级列表--登录用户为管理员时
     */
    getGrade(selectedType) {
        HttpService.query({
            url: '/jxt-api/rest/oauth',
            data: {
                method: 'org.list',
                req: '{"entry": "useradmin","schoolid":"' + sessionStorage.orgid + '"}',
                appkey: 'oauthsp',
                sign: '27d339e5fe3bf70991ce8af1694e50da',
                v: '1.0'
            },
            success: (res => {
                if (res.msgcode == '0000') {
                    let data = res.body[0];
                    if (data != null && data.length > 0) {
                        for (let i = 0; i < data.length; i++) {
                            let dataInfo = data[i];
                            if (dataInfo[3] == '年级') { //年级
                                if (this.state.footerGrade == '') {
                                    this.state.footerGrade.push({
                                        name: dataInfo[1],
                                        id: dataInfo[0],
                                        type: true,
                                        selected: selectedType,
                                        value: (this.state.footerGrade.length + 1) * 100 + 120000
                                    });
                                } else {
                                    this.state.footerGrade.push({
                                        name: dataInfo[1],
                                        id: dataInfo[0],
                                        type: true,
                                        selected: false,
                                        value: (this.state.footerGrade.length + 1) * 100 + 120000
                                    });
                                }

                            }
                        }
                        this.setState({
                            footerGrade: this.state.footerGrade
                        });
                    } else {
                        Tips('没有查找到年级相关数据！');
                    }
                } else {
                    Tips(res.msg);
                }
            })
        })
    }
    /**
     * 获取部门通讯录
     */
    getDepartmentPhone(info) {
        HttpService.query({
            url: '/jxt-api/rest/oauth',
            data: {
                method: 'org.list',
                req: '{"entry": "userinfo","schoolid":"' + info[2] + ',' + info[0] + '","isdept":"1","isSearch":"0","name":""}', //+' '+info[1]
                appkey: 'oauthsp',
                sign: 'be59de1b91e366f29d9e399037b54760',
                v: '1.0'
            },
            success: (res => {
                if (res.msgcode == '0000') {
                    this.state.listData = [];
                    let phoneList = res.body[0].list,
                        teacherList = res.body[1],
                        classList = res.body[2];
                    for (let classKey in classList) {
                        let classId = classKey,
                            className = classList[classKey].split(',')[0],
                            dataList = [];
                        for (let teacherKey in teacherList) {
                            let teacherId = teacherKey.split('_')[0];
                            if (teacherKey.split('_')[1] == classId) {
                                for (let i = 0; i < phoneList.length; i++) {
                                    if (phoneList[i][0] == teacherId && phoneList[i][4] == classId) {
                                        dataList.push({
                                            id: phoneList[i][0],
                                            name: phoneList[i][1],
                                            img: phoneList[i][1].substr(phoneList[i][1].length - 2, phoneList[i][1].length),
                                            phone: phoneList[i][2]
                                        });
                                    }
                                }
                            }
                        }
                        if (dataList != '') {
                            this.state.listData.push({
                                id: classId,
                                title: className,
                                show: true,
                                dataList: dataList
                            });
                        }
                    }
                    if (info[2] == '校管理员') {
                        for (let classKey in classList) {
                            let id = classKey,
                                deptname = classList[classKey].split(',')[0],
                                b = true;
                            for (let j = 0; j < this.state.footerDepartment.length; j++) {
                                if (id == this.state.footerDepartment[j].id) {
                                    b = false;
                                    break;
                                }
                            }
                            if (b) {
                                // footerDepartment.push({deptname:dataInfo[3],name:dataInfo[1],id:dataInfo[0],type:false,selected:selectedType,value:(footerDepartment.length+1)*100+110000});
                                this.state.footerDepartment.push({
                                    deptname: deptname,
                                    name: deptname,
                                    id: id,
                                    type: false,
                                    selected: false,
                                    value: (this.state.footerDepartment.length + 1) * 100 + 110000
                                });
                            }
                        }
                    }
                    this.setState({
                        listData: this.state.listData,
                        queryListData: this.state.listData,
                        footerMenu: 1,
                        footerDepartment: this.state.footerDepartment
                    });
                } else {
                    Tips(res.msg);
                    this.setState({
                        listData: [],
                        queryListData: []
                    });
                }
            })
        })
    }

    /**
     * 获取年级教师默认通讯录
     */
    getGradeTeacherPhone(id) {
        HttpService.query({
            url: '/jxt-api/rest/oauth',
            data: {
                method: 'org.list',
                req: '{"entry": "userinfo","schoolid":"' + id + '","isdept":"null","isSearch":"0","name":""}',
                appkey: 'oauthsp',
                sign: '50fb72a4f415910a9a5fba33bc5c4cf7',
                v: '1.0'
            },
            success: (res => {
                // if(res.msgcode == '0000'){
                //
                // }else{
                //     Tips(res.msg);
                // }
                this.getDataList(res, id, 2);
                this.setState({
                    footerMenu: 2
                });
            })
        })
    }
    /**
     * 获取班级家长or老师通讯录
     */
    getClassPhone(id) {
        HttpService.query({
            url: '/jxt-api/rest/oauth',
            data: {
                method: 'org.list',
                req: '{"entry": "userinfo","schoolid":"' + id + '","isdept":"null","isSearch":"0","name":""}',
                appkey: 'oauthsp',
                sign: 'd05877e1b79c804822564fc99a75aa15',
                v: '1.0'
            },
            success: (res => {
                // if(res.msgcode == '0000'){
                //
                // }else{
                //     Tips(res.msg);
                // }
                this.getDataList(res, id);
                // this.setState({footerMenu:3});
            })
        })
    }

    /**
     * 改变状态-老师或家长
     */
    setType(type) {
        const {
            footerClass,
            footerGrade,
            footerDepartment
        } = this.state;
        if (type) {
            let id = '';
            if (footerDepartment.length > 0) {
                id = footerDepartment[0].id;
                this.getDepartmentPhone([id, footerDepartment[0].name, footerDepartment[0].deptname]);
                this.setState({
                    footerMenu: 1
                });
            } else if (footerGrade.length > 0) {
                id = footerGrade[0].id;
                this.getGradeTeacherPhone(id);
                this.setState({
                    footerMenu: 2
                });
            } else if (footerClass.length > 0) {
                id = footerClass[0].id;
                this.getClassPhone(id);
                this.setState({
                    footerMenu: 3
                });
            }
            this.controlNextShow(id);
        } else {
            let id = '';
            if (footerGrade.length > 0) {
                id = footerGrade[0].id;
                this.getGradeTeacherPhone(id);
                this.setState({
                    footerMenu: 2
                });
            } else if (footerClass.length > 0) {
                id = footerClass[0].id;
                this.getClassPhone(id);
                this.setState({
                    footerMenu: 3
                });
            }
            this.controlNextShow(id);
        }
        this.setState({
            type: type,
            search: false
        });
        document.querySelector('#searchValue').value = ''; //清空输入框
        this.area.value = [0, 0];
    }

    /**
     * 搜索
     */
    search(e) {
        e.preventDefault();
        let searchValue = document.querySelector('#searchValue').value;
        this.getSearch(searchValue); //查询本地列表数据
        // HttpService.query({
        //     url: '/jxt-api/rest/oauth',
        //     data: {
        //         method: 'org.list',
        //         req: '{"entry": "userinfo","schoolid":"'+sessionStorage.orgid+'","isdept":"null","isSearch":"1","name":"'+document.querySelector('#searchValue').value+'"}',
        //         appkey: 'oauthsp',
        //         sign: '970d85e368d364b0607aff463d68b4d6',
        //         v: '1.0'
        //     },
        //     success: (res => {
        //         this.getDataList(res);
        //         document.querySelector('#searchValue').blur();
        //     })
        // });

    }

    /**
     * 查询本地列表数据
     * @param searchValue
     */
    getSearch(searchValue) {
        let queryListData = this.state.queryListData;
        this.state.listData = [];
        for (let i = 0; i < queryListData.length; i++) {
            let dataList = queryListData[i].dataList,
                dataListNew = [];
            let isHaveValue = false;
            for (let j = 0; j < dataList.length; j++) {
                let username = dataList[j].name;
                if (username.indexOf(searchValue) > -1) {
                    isHaveValue = true;
                    dataListNew.push({
                        id: dataList[j].id,
                        name: dataList[j].name,
                        img: dataList[j].img,
                        phone: dataList[j].phone
                    });
                }
            }
            if (isHaveValue) {
                this.state.listData.push({
                    id: queryListData[i].id,
                    title: queryListData[i].title,
                    show: queryListData[i].show,
                    dataList: dataListNew
                });
            }
        }
        this.setState({
            listData: this.state.listData
        });
    }
    /**
     * 组装列表数据
     */
    getDataList(res, id, type) {
        if (res.msgcode == '0000') {
            this.state.listData = [];
            let phoneList = res.body[0].list,
                teacherList = res.body[1],
                classList = res.body[2];
            if (this.state.type) { //header教师
                for (let classKey in classList) {
                    let classId = classKey,
                        className = classList[classKey].split(',')[0],
                        dataList = [];
                    for (let teacherKey in teacherList) {
                        let teacherId = teacherKey.split('_')[0];
                        let identity = teacherList[teacherKey];
                        identity = identity.replace('0', ''); //有的数据班主任前面有0，例如：0班主任
                        if (teacherKey.split('_')[1] == classId) {
                            for (let i = 0; i < phoneList.length; i++) {
                                if (phoneList[i][0] == teacherId && phoneList[i][4] == classId) {
                                    dataList.push({
                                        id: phoneList[i][0],
                                        name: phoneList[i][1],
                                        img: phoneList[i][1].substr(phoneList[i][1].length - 2, phoneList[i][1].length),
                                        phone: phoneList[i][2],
                                        identity: identity
                                    });
                                }
                            }
                        }
                    }
                    if (dataList != '') {
                        this.state.listData.push({
                            id: classId,
                            title: className,
                            show: true,
                            dataList: dataList
                        });
                    }
                }
            } else { //header家长
                for (let classKey in classList) {
                    let classId = classKey,
                        className = classList[classKey].split(',')[0],
                        dataList = [];
                    for (let i = 0; i < phoneList.length; i++) {
                        if (phoneList[i][4] == classId) {
                            let b = true;
                            for (let teacherKey in teacherList) {
                                let teacherId = teacherKey.split('_')[0];
                                if (phoneList[i][0] == teacherId) {
                                    b = false;
                                    break;
                                }
                            }
                            if (b) {
                                dataList.push({
                                    id: phoneList[i][0],
                                    name: phoneList[i][1],
                                    img: phoneList[i][1].substr(phoneList[i][1].length - 2, phoneList[i][1].length),
                                    phone: phoneList[i][2],
                                    identity: ''
                                });
                                b = true;
                            }
                        }
                    }
                    if (dataList != '') {
                        this.state.listData.push({
                            id: classId,
                            title: className,
                            show: true,
                            dataList: dataList
                        });
                    }
                }
            }

            if (this.state.listData.length == 0) {
                //Tips('未查询到信息',1);
            }
            //年级下面的班级倒叙
            if (type == '2') {
                let tarray = [];
                for (let i = this.state.listData.length - 1; i >= 0; i--) {
                    tarray.push({
                        id: this.state.listData[i].id,
                        title: this.state.listData[i].title,
                        show: this.state.listData[i].show,
                        dataList: this.state.listData[i].dataList
                    });
                }
                this.setState({
                    listData: tarray,
                    queryListData: this.state.listData
                });
            } else {
                this.setState({
                    listData: this.state.listData,
                    queryListData: this.state.listData
                });
            }

        } else {
            Tips(res.msg, 1);
            this.setState({
                listData: [],
                queryListData: []
            });
        }
    }

    /**
     * 点击部门或班级
     */
    openFotterList(type) {
        // if(type){
        // this.setState({footerList:true});
        // }
        let gearAreas = document.querySelectorAll('.gearArea');
        for (let i = 0; i < gearAreas.length - 1; i++) {
            document.body.removeChild(gearAreas[i]);
        }
        let rct = this;
        //绑定事件——改变后就去更新数据
        document.querySelector('.larea_finish').addEventListener('touchstart', function() {
            let footer_select = document.querySelector('#footer_select').value;
            if (footer_select.split('_')[0] == '部门') {
                rct.getDepartmentPhone([footer_select.split('_')[1], '', footer_select.split('_')[2]]);
            } else if (footer_select.split('_')[0] == '年级') {
                rct.getGradeTeacherPhone(footer_select.split('_')[1]);
            } else {
                rct.getClassPhone(footer_select.split('_')[1]);
            }

            // document.querySelector('.phone_directories_content').style.overflow = 'scroll';//禁用class为phone_directories_content的滚动条
            // document.querySelector('.phone_directories_content').style.height = 'auto';//禁用class为phone_directories_content的滚动条
            document.body.removeEventListener('touchmove', rct.bodyEven, false);
            document.getElementsByTagName('body')[0].style.overflow = 'scroll'; //启用body元素的滚动条
        });
        // //绑定事件——改变后就去更新数据
        document.querySelector('.larea_cancel').addEventListener('touchstart', function() {

            // document.querySelector('.phone_directories_content').style.overflow = 'scroll';//禁用class为phone_directories_content的滚动条
            // document.querySelector('.phone_directories_content').style.height = 'auto';//禁用class为phone_directories_content的滚动条
            document.body.removeEventListener('touchmove', rct.bodyEven, false);
            document.getElementsByTagName('body')[0].style.overflow = 'scroll'; //启用body元素的滚动条
        });
        // //绑定事件——改变后就去更新数据
        document.querySelector('.maskin_area').addEventListener('click', function() {
            // document.querySelector('.phone_directories_content').style.overflow = 'scroll';//禁用class为phone_directories_content的滚动条
            // document.querySelector('.phone_directories_content').style.height = 'auto';//禁用class为phone_directories_content的滚动条
            let gearArea = document.querySelector('.gearArea');
            document.body.removeChild(gearArea);

            document.body.removeEventListener('touchmove', rct.bodyEven, false);
            document.getElementsByTagName('body')[0].style.overflow = 'scroll'; //启用body元素的滚动条
        });
        document.body.addEventListener('touchmove', rct.bodyEven, false);
        document.getElementsByTagName('body')[0].style.overflow = 'hidden'; //启用body元素的滚动条
        // document.querySelector('.phone_directories_content').style.overflow = 'hidden';//禁用class为phone_directories_content的滚动条
        // document.querySelector('.phone_directories_content').style.height = window.screen.height-200+'px';//禁用class为phone_directories_content的滚动条

    }

    /**
     * body touchmove 事件
     * @param event
     */
    bodyEven(event) {
        event.preventDefault();
    }
    /**
     * 点击列表隐藏或显示
     */
    controlNextShow(id) {
        const {
            listData
        } = this.state;
        for (let i = 0; i < listData.length; i++) {
            if (listData[i].id == id) {
                if (this.state.listData[i].show == true) {
                    this.state.listData[i].show = false;
                } else {
                    this.state.listData[i].show = true;
                }
            }
        }
        this.setState({
            listData: listData,
            queryListData: this.state.listData
        });
    }

    /**
     * 搜索
     */
    changeSearch(e) {
        if (e.target.value.length > 0) {
            this.setState({
                search: true
            });
        } else {
            this.setState({
                search: false
            });
        }
        this.getSearch(e.target.value);
    }

    /**
     * 清空输入框-并改变状态
     */
    searchEmpty() {
        document.querySelector('#searchValue').value = '';
        this.setState({
            search: false,
            listData: this.state.queryListData
        });
        // this.setType(this.state.type);
    }
    /**
     * 清空输入框
     */
    searchClose() {
        let searchValue = document.querySelector('#searchValue');
        searchValue.value = '';
        this.getSearch(''); //重置列表
        searchValue.focus();
    }
    /**
     * 弹出框改变样式
     */
    footerMenu(type) {
        this.setState({
            footerMenu: type
        });
    }
    /**
     * 点击打电话
     * 如果是微信打开就不弹出透明层防止多次点击
     */
    clickTel() {
        let rct = this;
        if (!browser().weixin) {
            rct.setState({
                showModule: true
            });
            setTimeout(function() {
                rct.setState({
                    showModule: false
                });
            }, 2000)
        }
    }

    render() {
        const {
            type,
            footerClass,
            footerGrade,
            footerDepartment,
            listData,
            search,
            footerMenu,
            showModule
        } = this.state;
        let showFooter = true;
        if (type && footerClass == '' && footerGrade == '' && footerDepartment == '') {
            showFooter = false;
        } else if (footerClass == '' && footerGrade == '') {
            showFooter = false;
        }
        const publishLink = <a className={showFooter==true?'h_link color_blue':'h_link color_gary'} onClick={this.openFotterList.bind(this,showFooter)}>{type==true?'部门':'班级'}</a>;
        const listDatas = listData.map((item) => {
            return (
                <div className="content_list">
                    <div className={item.show==true?"list_title is_open ":"list_title is_open takeback_blue"}  onClick={this.controlNextShow.bind(this,item.id)}>{item.title}</div>
                    <ul style={{display:item.show==true?'block':'none'}}>
                        {
                            item.dataList.map((user,index) => {
                                return(
                                    <li>
                                        <a href={'tel:'+user.phone} onClick={this.clickTel.bind(this)}>
                                            {/*<img src={getDefaultImg()} className="username_img"/>*/}
                                            <span className="username_img_span">{user.img}</span>
                                            <div className={item.dataList.length-1==index?'phone_info noBorder':'phone_info'}>
                                                <span className="username">{user.name}{user.identity?<span className="identity">&nbsp;({user.identity})</span>:''}    {type==false?'的家长':''}</span>
                                                <span className="phone_number">{user.phone}</span>
                                            </div>
                                            {sessionStorage.app=='true'?<span onClick={this.pushToChatRoom.bind(this,user.phone+'&'+user.name)} className='chat'></span>:null}
                                        </a>
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
            )
        });

        return (
            <div className='phone_directories'>
                {
                    showModule==true?
                        <div className="maskin phone_module"></div>
                        :''
                }
                {
                    sessionStorage.userrole != '家长'?
                    <Header link={sessionStorage.userrole == '家长'?'':publishLink} appLink='1'>
                        <div className="phone_type">
                            <div className={type==true?'select':''} onClick={this.setType.bind(this,true)}>老师</div>
                            <div className={type==true?'':'select'} onClick={this.setType.bind(this,false)}>家长</div>
                        </div>
                    </Header>
                        :<Header link={sessionStorage.userrole == '家长'?'':publishLink} title="教师通讯录" appLink='1'/>
                }
                <div className={search==true?'query have_value':'query'}>
                    <form className="searchForm" action="" autoComplete='off' onSubmit={this.search.bind(this)} >
                        <div className="query_content ">
                            <input type="search" id="searchValue" autoComplete='off' className='left' maxLength='30' onChange={this.changeSearch.bind(this)} placeholder="请输入关键字"/>
                            <span className="close_img " onClick={this.searchClose.bind(this)}/>
                        </div>
                    </form>
                    <span className="cancel" onClick={this.searchEmpty.bind(this)}>取消</span>
                </div>
                <div className="phone_directories_content">
                    {
                        listDatas==''?<p>暂无信息</p>:listDatas
                    }
                </div>
                <input type="hidden"  id="footer_select" />
            </div>
        )
    }
}
